library(haven)
library(sp)
library(rgdal)
library(rgeos)
library(RColorBrewer)
library(cshapes)
library(maptools)
library(raster)
library(RColorBrewer)
library(gtools)

###################################################
##########        POLYARCHY MAP      ##############
###################################################


vd <- read_dta("data/mapdata.dta")
vd <- subset(vd, year==2019, select=c(country, v2x_polyarchy_imp_100, country_id))

c <- readOGR("data/shapefiles/maps1946_2018.shp", layer="maps1946_2018")
c2 <- subset(c, c@data$year==2018 )


c <- c2@data
colnames(c2@data)[1] <- "country_id"

c2 <- merge(c2, vd, by=c("country_id"), all.x=T)


c2@data$v2x_polyarchy[c2@data$country=="Norway"] <- 0.93
c2@data$v2x_polyarchy[c2@data$country=="Somalia"] <- 0.15
c2@data$v2x_polyarchy[c2@data$country=="Morocco"] <- 0.45
c2@data$v2x_polyarchy[c2@data$country=="Seychelles"] <- 0.95


c2 <- subset(c2, c2@data$orgnl__ != "Antarctica")
c2 <- subset(c2, c2@data$orgnl__ != "Eskimos")
c2 <- subset(c2, c2@data$orgnl__ != "Greenland")
c2 <- subset(c2, c2@data$orgnl__ != "Germany Federal Republic")


d <- c2@data
my.palette <- brewer.pal(n = 8, name = "Greys")
library(classInt)
breaks.qt <- classIntervals(c2@data$v2x_polyarchy,
                            n = 7,
                            style = "quantile",
                            intervalClosure = "right")

tiff("output/map_2_2.tiff", width = 8, height = 5.5, units = 'in', res = 300)
par(mar = rep(0, 4))
spplot(c2, "v2x_polyarchy_imp_100", main = " ", 
       col.regions = my.palette, 
       at = breaks.qt$brks)
dev.off()
